--local GameControl = require("app.GameControl")
local Event = require("app.event.Event")
local EventListener = require("app.event.EventListener")

local EventDispatcher = class("EventDispatcher")--,GameControl)
--全局的实例
EventDispatcher.instance = nil

function EventDispatcher:ctor()
    self._listeners = {}
end

function EventDispatcher:GetInstance()
	if EventDispatcher.instance == nil then
		EventDispatcher.instance = EventDispatcher.new()--td.GameControlType.ExitGame)
	end

	return EventDispatcher.instance
end

function EventDispatcher:ClearValue()

end

function EventDispatcher:AddEventListener(eventName, func)
    local listener = EventListener.new(eventName, func)
	if not self._listeners[eventName] then
		self._listeners[eventName] = {}
	end
	table.insert(self._listeners[eventName],listener)
    return listener
end

function EventDispatcher:RemoveEventListener(listener)
	local listeners = self._listeners[listener:GetName()]
	if not listeners then
		return
	end

    for index, handle in ipairs(listeners) do
        if handle == listener then
            table.remove(listeners, index)
            break
        end
    end
end

function EventDispatcher:RemoveAllEventListenersForEvent(eventName)
	self._listeners[eventName] = nil
end

function EventDispatcher:RemoveAllEventListeners()
    self._listeners = {}
end

function EventDispatcher:DispatchEvent(eventName,data)
	local listeners = self._listeners[eventName]
	if not listeners then
		return
	end

	local event = Event.new(eventName,data)
	for _, listener in ipairs(listeners) do
		listener:OnWork(event)
	end
end

return EventDispatcher

